<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24
 * Time: 16:57
 */
namespace frontend\services;

use backend\models\Baseproducts;
use backend\common\PubService;
use backend\models\PackItem;
use backend\models\PlayerTbl;
use yii;

class OderService
{
    public function checkInfo($data)
    {
        //获取客户端数据
        if (empty($data)){
            return ['statusCode'=>401];
        }
        $player = PlayerTbl::findOne(['PlayerID'=>$data['UserId']]);
        if (!$player){
            return ['statusCode'=>401,'message'=>'玩家不合法'];
        }
        if (strpos($data['ProductId'], '_')){
            $product = explode('_', $data['ProductId']);
            $data['ProductId'] = $product[1];//华为/小米支付 商品id格式：hw_1118/xm_1209
        }
        $arrData['RequestId'] = isset($data['RequestId']) ? $data['RequestId'] : 0;
        $arrData['UserId'] = $data['UserId'] ;
        $arrData['ProductId'] = $data['ProductId'] ;
        $arrData['ClassId'] = $data['ClassId'] ;//支付方式(0微信H5 1支付宝H5 2苹果内购 3微信APP 4微信公众号 5小程序 6华为支付 7小米支付)"
        $arrData['OriginId'] = $data['ClientId'];//客户端类型(0安卓 1苹果 2其他);
        $product = Baseproducts::findOne(['ProductId'=>$data['ProductId']]);
        $arrData['Amount'] = $product->Amount;
        $arrData['NumCount'] = $product->NumCount;
        $arrData['ExtraCount'] = $product->ExtraCount;
        $arrData['CollectDate'] = date('Y-m-d H:i:s', time());
        $arrData['AddrIP'] = PubService::real_ip();
        foreach (yii::$app->params['pay_status'] as $key => $val) {
            if ($key == $data['ClassId']){
                $arrData['Description'] = yii::$app->params['pay_status'][$key];
                break;
            }
        }
        $orderId = self::insertOrderData($arrData);
        if ($orderId){
            return ['statusCode'=>1, 'message'=>'成功生成订单', 'OrderId'=>$orderId];
        }
        return ['statusCode'=>0, 'message' => '网络异常'];
    }


    public static function insertOrderData($allData)
    {
        $db = yii::$app->db;
        $allData['OrderId'] = 'kwx_'.date('ymdHis',time()) . substr(str_shuffle('0123456789'), 0, 6);
        $transaction = $db->beginTransaction();
        try{
            $db->createCommand()->insert('baseorders',$allData)->execute();
            $transaction->commit();
            return $allData['OrderId'];
        }catch (\Exception $e){
            $transaction->rollBack();
            return false;
        }
    }


}